import { Inject, Controller, Get, Query, Post, Body } from '@midwayjs/core';
import { Context } from '@midwayjs/koa';
import { PREFIX } from '../contanst';
import { BaseController } from './base.controller';
import { FileService } from '../service/file.service';
import { InventoryService } from '../service/inventory.service';
import { divide, times } from '../utils/math';
import { Like } from 'typeorm';

const DESCRIPTION = '库存';
@Controller(PREFIX)
export class APIController extends BaseController {
  @Inject()
  ctx: Context;

  @Inject()
  inventoryService: InventoryService;

  @Get('/inventory', {
    description: `${DESCRIPTION}列表`,
  })
  async index(
    @Query('size') size = 10,
    @Query('page') page = 1,
    @Query('warehousing_time') warehousing_time,
    @Query('product_code') product_code
  ) {
    const list = await this.inventoryService.page({
      data: {
        size,
        page,
        warehousing_time,
        product_code: product_code && Like(`%${product_code}%`),
      },
    });
    return this.success(list);
  }

  @Inject()
  file: FileService;

  @Post('/inventory', {
    description: `${DESCRIPTION}新增`,
  })
  async import(@Body('data') data: any[]) {
    const records = data.map(item => {
      const box_gauge = item.box_gauge || 0;
      const product_quantity = item.product_quantity || 0;
      // 库存量
      const remaining_inventory_quantity = times(box_gauge, product_quantity);
      // 单价
      item.unit_price = divide(item.buying_price, box_gauge);
      return { ...item, remaining_inventory_quantity };
    });
    this.inventoryService.upsert(records);

    return this.success(records);
  }
}
